package com.polaris.live.im.utils

import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.im.db.entity.MessageEntity
import com.polaris.live.im.db.entity.SessionEntity
import com.polaris.live.im.manager.ImSessionManager
import com.polaris.live.im.sfs.MESSAGE_STATUS_SENDING
import com.polaris.live.im.sfs.MESSAGE_STATUS_SUCCESS
import com.polaris.live.im.sfs.TYPE_MESSAGE_CALL
import com.polaris.live.im.sfs.TYPE_MESSAGE_GIFT
import com.polaris.live.im.sfs.bean.chat.ReceiveSingleMessage
import com.polaris.live.im.sfs.bean.chat.SingleMessage
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.utils.BitwiseUtils
import java.util.concurrent.TimeUnit

/**
 * 这里主要用于存数据库前 给entity赋值
 *
 * @author Created by 半仙 on 2023/8/26/026 17:30
 */
object MessageEntityUtils {

    fun genStrangerContent(
        userBasic: UserBasicVo?,
        translateContent: String?,
        content: String,
    ): String {
        return genStrangerContent(userBasic, translateContent ?: content)
    }

    fun genStrangerContent(userBasic: UserBasicVo?, content: String): String {
        return if (userBasic != null) {
            userBasic.nickname + ": "
        } else {
            ""
        } + content
    }

    /**
     * 查找列表中是打招呼消息并且还未读的
     */
    fun filterListGreetPushMessageFlag(list: List<MessageEntity>): List<MessageEntity> {
        return list.filter {
            it.payloadBean?.flagGreetPushMessage == "1"
        }
    }
}

fun ReceiveSingleMessage.toMessageEntity(): MessageEntity {
    return MessageEntity(
        command = command,
        userId = UserManager.getUserId(),
        otherId = getOtherId(),
        sender = sender,
        recipient = recipient,
        type = type,
        content = message.content,
        state = MESSAGE_STATUS_SUCCESS,
        msgId = msgId,
        timestamp = message.timestamp,
        seqId = seqId,
        ext = message.ext,
        payload = message.payload,
        parameter = parameter,
        translateContent = translateContent
    )
}

fun ReceiveSingleMessage.toSessionEntity(
    userJson: String? = null,
    unreadCount: Long? = null,
    strangerUnreadCount: Long? = null,
): SessionEntity {
    val userId = UserManager.getUserId()

    val content = if (!translateContent.isNullOrEmpty() && sender != userId) {
        translateContent
    } else {
        message.content
    }

    val greetPushMessage = getGreetPushMessageFlag()

    //计算是否为陌生人消息
    val isStranger = if (sender == userId || (hotLevel != null && hotLevel >= 1)) {
        false
    } else if (BitwiseUtils.isBitwise(type, TYPE_MESSAGE_GIFT)
        || BitwiseUtils.isBitwise(type, TYPE_MESSAGE_CALL)
    ) {
        false
    } else {
        if (greetPushMessage == true
            && message.timestamp > CacheUtil.getServerTime() - TimeUnit.HOURS.toMillis(1)
        ) {
            false
        } else {
            null
        }
    }

    val newSessionEntity = newSessionEntity

    return SessionEntity(
        command = command,
        userId = UserManager.getUserId(),
        otherId = getOtherId(),
        senderId = sender,
        type = type,
        content = content,
        timestamp = message.timestamp,
        seqId = seqId,
        ext = message.ext,
        payload = message.payload,
        unreadCount = unreadCount,
        strangerUnreadCount = strangerUnreadCount,
        strangerStatus = if (newSessionEntity != null) newSessionEntity.strangerStatus else isStranger,
        greetPushMessage = greetPushMessage,
        userJson = userJson
    ).also {
        it.isTranAcquaintance = newSessionEntity?.isTranAcquaintance ?: false
        it.updateUserBasic(newSessionEntity?.userBasic)

    }
}

private fun ReceiveSingleMessage.getGreetPushMessageFlag(): Boolean? {
    val greetFlag = message.payload?.let {
        JsonUtils.readPrimitiveFromJsonObject(
            it,
            com.polaris.live.im.sfs.EXT_FLAG_GREET_PUSH_MESSAGE
        )
    }
    return if (greetFlag == "1" || greetFlag == com.polaris.live.im.sfs.EXT_FLAG_PUSH_MESSAGE) {
        true
    } else {
        null
    }
}

/**
 * toMessage，自己发送的
 */
fun SingleMessage.toSelfMessageEntity(command: String, parameter: String? = null): MessageEntity {
    val sender = UserManager.getUser().userId ?: 0

    return MessageEntity(
        command = command,
        userId = sender,
        otherId = recipient,
        sender = sender,
        recipient = recipient,
        type = type,
        content = content,
        state = MESSAGE_STATUS_SENDING,
        msgId = msgId,
        timestamp = timestamp,
        seqId = seqId,
        ext = ext,
        payload = payload,
        parameter = parameter
    )
}

/**
 * toSingleMessage，自己发送的
 */
fun MessageEntity.toSelfSingleMessage(): SingleMessage {
    return SingleMessage(
        recipient = recipient,
        type = type,
        content = content,
        payload = payload,
        ext = ext,
        seqId = seqId,
        msgId = msgId,
        timestamp = timestamp
    )
}

/**
 * toSession 自己发送的
 */
fun SingleMessage.toSelfSessionEntity(command: String): SessionEntity {
    return SessionEntity(
        command = command,
        userId = UserManager.getUserId(),
        otherId = recipient,
        senderId = UserManager.getUserId(),
        type = type,
        content = content,
        timestamp = timestamp,
        seqId = seqId,
        ext = ext,
        payload = payload,
        //自己发送后这2个值将变化
        strangerStatus = false,
        greetPushMessage = null
    )
}

fun MessageEntity.toSelfSessionEntity(userJson: String): SessionEntity {
    return SessionEntity(
        command = command,
        userId = UserManager.getUserId(),
        otherId = recipient,
        senderId = UserManager.getUserId(),
        type = type,
        content = content,
        timestamp = timestamp,
        seqId = seqId,
        ext = ext,
        payload = payload,
        unreadCount = null,
        strangerUnreadCount = null,
        strangerStatus = false,
        userJson = userJson
    )
}

fun SessionEntity.toNewSession(messageEntity: MessageEntity): SessionEntity {
    return copy(
        type = messageEntity.type,
        content = messageEntity.content,
        senderId = messageEntity.sender,
        timestamp = messageEntity.timestamp,
        seqId = messageEntity.seqId,
        ext = messageEntity.ext,
        payload = messageEntity.payload,
        userJson = userJson,
    ).apply {
        updateUserBasic(null)
    }
}

fun SessionEntity.toEmptySession(): SessionEntity {
    return copy(
        type = null,
        content = null,
        senderId = null,
        timestamp = null,
        seqId = null,
        ext = null,
        payload = null,
        unreadCount = null,
        userJson = null
    ).apply {
        updateUserBasic(null)
    }
}

fun SessionEntity.toStrangerSession(
    messageEntity: MessageEntity,
    userBasic: UserBasicVo?,
): SessionEntity {
    val content =
        MessageEntityUtils.genStrangerContent(
            userBasic,
            messageEntity.translateContent,
            messageEntity.content
        )

    return copy(
        otherId = messageEntity.otherId,
        type = messageEntity.type,
        content = content,
        senderId = messageEntity.sender,
        timestamp = messageEntity.timestamp,
        seqId = messageEntity.seqId,
        ext = messageEntity.ext,
        payload = messageEntity.payload,
        unreadCount = ImSessionManager.getStrangerUnreadCount()
    )
}

fun SessionEntity.toStrangerSession(sessionEntity: SessionEntity): SessionEntity {
    val content =
        MessageEntityUtils.genStrangerContent(sessionEntity.userBasic, sessionEntity.content ?: "")

    return copy(
        otherId = sessionEntity.otherId,
        type = sessionEntity.type,
        content = content,
        senderId = sessionEntity.senderId,
        timestamp = sessionEntity.timestamp,
        seqId = sessionEntity.seqId,
        ext = sessionEntity.ext,
        payload = sessionEntity.payload,
        unreadCount = ImSessionManager.getStrangerUnreadCount()
    )
}